
package splash.core;

import java.util.Date;

import java.text.SimpleDateFormat;

import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException;

import java.net.ServerSocket;
import java.net.BindException;

import java.io.IOException;

public class Util
{
	public static String getTimestamp()
	{
		return new SimpleDateFormat("dd.MM.yyyy - HH:mm:ss").format(new Date());
	}
	
	/*
	*	Pri dodajanju algoritmov je treba poskrbeti, da hashing algoritem obstaja
	*/
	
	private static String hash(String plain, String alg)
	{
		if(plain == null)
			throw new NullPointerException();
	
		MessageDigest d = null;
		try
		{
			d = MessageDigest.getInstance(alg);
		}
		catch(NoSuchAlgorithmException e)
		{
			//ignore
			e.printStackTrace();
		}

                d.update(plain.getBytes());
		byte[] bts = d.digest();
                String out = "";

                for (int i = 0; i < bts.length; i++)
                        out += (Integer.toString((bts[i] & 0xff) + 0x100, 16).substring(1));

                return out;
    	}

	public static int passwordStrength(String password)
        {
            int strength = 0;
  
            if(password.matches(".*\\W.*"))
                strength += 2;
            if(password.matches(".*[A-Z].*"))
                strength += 2;
            if(password.matches(".*\\d.*"))
                strength += 2;
            if(password.matches(".*[a-z].*"))
                strength += 2;
            
            strength += (password.length() / 4);
            
            return (strength < 11) ? strength : 10;
        }
	
	/* SHA and MD5 */
	
	public static String sha(String plain)
	{
		return hash(plain, "SHA-1");
	}
	
	public static String md5(String plain)
	{
		return hash(plain,"MD5");
	}
        
	public static boolean isBound(int port)
	{
		if(port <= 0 || port > 65535)
			return true;
		ServerSocket s = null;
		try
		{
			s = new ServerSocket(port);
			s.setSoTimeout(5);
			s.accept();
			s.close();
			return false;
		}
		catch(java.net.SocketTimeoutException ste)
		{
			try
			{
				if(s != null)
					s.close();
			}
			catch(IOException e) {}
			return false;
		}
		catch(BindException be)
		{
			try
			{
				if(s != null)
					s.close();
			}
			catch(IOException e) {}
			return true;
		}
		catch(IOException e)
		{
			try
			{
				if(s != null)
					s.close();
			}
			catch(IOException ei) {}
			return true;
		}
	}
}